import { redisClient } from '../config/redis';
import { generateTimestampNumericUUID } from '../utils/uuid';

export class TokenService {
  // Token过期时间（秒）- 默认7天
  private static readonly TOKEN_EXPIRY = 7 * 24 * 60 * 60;
  
  // Token前缀
  private static readonly TOKEN_PREFIX = 'user_token:';

  /**
   * 生成用户token
   * @param userId 用户ID
   * @returns token字符串
   */
  public static async generateToken(userId: string): Promise<string> {
    const token = generateTimestampNumericUUID();
    const key = this.TOKEN_PREFIX + token;
    
    // 在Redis中存储token，值为用户ID，设置过期时间
    await redisClient.setEx(key, this.TOKEN_EXPIRY, userId);
    
    return token;
  }

  /**
   * 验证token并获取用户ID
   * @param token token字符串
   * @returns 用户ID或null
   */
  public static async validateToken(token: string): Promise<string | null> {
    const key = this.TOKEN_PREFIX + token;
    const userId = await redisClient.get(key);
    
    if (userId) {
      // 刷新token过期时间
      await redisClient.expire(key, this.TOKEN_EXPIRY);
    }
    
    return userId;
  }

  /**
   * 删除token（用户登出）
   * @param token token字符串
   */
  public static async deleteToken(token: string): Promise<void> {
    const key = this.TOKEN_PREFIX + token;
    await redisClient.del(key);
  }

  /**
   * 删除用户的所有token
   * @param userId 用户ID
   */
  public static async deleteAllUserTokens(userId: string): Promise<void> {
    const pattern = this.TOKEN_PREFIX + '*';
    const keys = await redisClient.keys(pattern);
    
    for (const key of keys) {
      const storedUserId = await redisClient.get(key);
      if (storedUserId === userId) {
        await redisClient.del(key);
      }
    }
  }
}